/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.persistence.controller;

import com.smarttmt.idu.ejb.domain.Constants;
import com.smarttmt.idu.web.persistence.controller.exceptions.IllegalOrphanException;
import com.smarttmt.idu.web.persistence.controller.exceptions.NonexistentEntityException;
import com.smarttmt.idu.web.persistence.controller.exceptions.PreexistingEntityException;
import com.smarttmt.idu.web.persistence.controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.smarttmt.idu.web.persistence.entity.Uscochip;
import com.smarttmt.idu.web.persistence.entity.Usuacont;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
public class UsuacontJpaController implements Serializable {

    public UsuacontJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Usuacont usuacont) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (usuacont.getUscochipList() == null) {
            usuacont.setUscochipList(new ArrayList<Uscochip>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Uscochip> attachedUscochipList = new ArrayList<Uscochip>();
            for (Uscochip uscochipListUscochipToAttach : usuacont.getUscochipList()) {
                uscochipListUscochipToAttach = em.getReference(uscochipListUscochipToAttach.getClass(), uscochipListUscochipToAttach.getUscochipPK());
                attachedUscochipList.add(uscochipListUscochipToAttach);
            }
            usuacont.setUscochipList(attachedUscochipList);
            em.persist(usuacont);
            for (Uscochip uscochipListUscochip : usuacont.getUscochipList()) {
                Usuacont oldUsuacontOfUscochipListUscochip = uscochipListUscochip.getUsuacont();
                uscochipListUscochip.setUsuacont(usuacont);
                uscochipListUscochip = em.merge(uscochipListUscochip);
                if (oldUsuacontOfUscochipListUscochip != null) {
                    oldUsuacontOfUscochipListUscochip.getUscochipList().remove(uscochipListUscochip);
                    oldUsuacontOfUscochipListUscochip = em.merge(oldUsuacontOfUscochipListUscochip);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findUsuacont(usuacont.getUscocodi()) != null) {
                throw new PreexistingEntityException("Usuacont " + usuacont + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Usuacont usuacont) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Usuacont persistentUsuacont = em.find(Usuacont.class, usuacont.getUscocodi());
            List<Uscochip> uscochipListOld = persistentUsuacont.getUscochipList();
            List<Uscochip> uscochipListNew = usuacont.getUscochipList();
            List<String> illegalOrphanMessages = null;
            for (Uscochip uscochipListOldUscochip : uscochipListOld) {
                if (!uscochipListNew.contains(uscochipListOldUscochip)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Uscochip " + uscochipListOldUscochip + " since its usuacont field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Uscochip> attachedUscochipListNew = new ArrayList<Uscochip>();
            for (Uscochip uscochipListNewUscochipToAttach : uscochipListNew) {
                uscochipListNewUscochipToAttach = em.getReference(uscochipListNewUscochipToAttach.getClass(), uscochipListNewUscochipToAttach.getUscochipPK());
                attachedUscochipListNew.add(uscochipListNewUscochipToAttach);
            }
            uscochipListNew = attachedUscochipListNew;
            usuacont.setUscochipList(uscochipListNew);
            usuacont = em.merge(usuacont);
            for (Uscochip uscochipListNewUscochip : uscochipListNew) {
                if (!uscochipListOld.contains(uscochipListNewUscochip)) {
                    Usuacont oldUsuacontOfUscochipListNewUscochip = uscochipListNewUscochip.getUsuacont();
                    uscochipListNewUscochip.setUsuacont(usuacont);
                    uscochipListNewUscochip = em.merge(uscochipListNewUscochip);
                    if (oldUsuacontOfUscochipListNewUscochip != null && !oldUsuacontOfUscochipListNewUscochip.equals(usuacont)) {
                        oldUsuacontOfUscochipListNewUscochip.getUscochipList().remove(uscochipListNewUscochip);
                        oldUsuacontOfUscochipListNewUscochip = em.merge(oldUsuacontOfUscochipListNewUscochip);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                BigDecimal id = usuacont.getUscocodi();
                if (findUsuacont(id) == null) {
                    throw new NonexistentEntityException("The usuacont with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(BigDecimal id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Usuacont usuacont;
            try {
                usuacont = em.getReference(Usuacont.class, id);
                usuacont.getUscocodi();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The usuacont with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Uscochip> uscochipListOrphanCheck = usuacont.getUscochipList();
            for (Uscochip uscochipListOrphanCheckUscochip : uscochipListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Usuacont (" + usuacont + ") cannot be destroyed since the Uscochip " + uscochipListOrphanCheckUscochip + " in its uscochipList field has a non-nullable usuacont field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(usuacont);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Usuacont> findUsuacontEntities() {
        return findUsuacontEntities(true, -1, -1);
    }

    public List<Usuacont> findUsuacontEntities(int maxResults, int firstResult) {
        return findUsuacontEntities(false, maxResults, firstResult);
    }

    private List<Usuacont> findUsuacontEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Usuacont.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Usuacont findUsuacont(BigDecimal id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Usuacont.class, id);
        } finally {
            em.close();
        }
    }

    public boolean existUserByNomb(String usconomb) {
        EntityManager em = getEntityManager();
        try {
            return (!em.createNamedQuery("Usuacont.findByUsconomb", Usuacont.class).setParameter("usconomb", usconomb).getResultList().isEmpty());
        } finally {
            em.close();
        }
    }

    public String getUserEmailByNomb(String usconomb) {
        Usuacont usu;
        java.util.List<Usuacont> usualist;
        EntityManager em = getEntityManager();
        try {
            usualist = em.createQuery("SELECT u FROM Usuacont u WHERE u.usconomb = :usconomb OR u.uscomail = :usconomb", Usuacont.class).setParameter("usconomb", usconomb).getResultList();
            if(!usualist.isEmpty()){
                usu = usualist.get(0);
                return usu.getUscomail();
            }else{
                return null;
            }        
        } finally {
            em.close();
        }
    }
    
    public String getUserByNombOrEmail(String usconomb) {
        Usuacont usu;
        EntityManager em = getEntityManager();
        try {
            usu = em.createQuery("SELECT u FROM Usuacont u WHERE u.usconomb = :usconomb OR u.uscomail = :usconomb", Usuacont.class).setParameter("usconomb", usconomb).getResultList().get(0);
            return usu.getUsconomb();        
        } finally {
            em.close();
        }
    }

    public boolean needToCompleteAditionalInfo(String usconomb) {
        EntityManager em = getEntityManager();
        try {
            Usuacont usu = em.createNamedQuery("Usuacont.findByUsconomb", Usuacont.class).setParameter("usconomb", usconomb).getResultList().get(0);
            return !(usu.getUscoprnm() != null && usu.getUscoprap() != null && usu.getUscodire() != null);
        } finally {
            em.close();
        }
    }

    public Usuacont getUserByUsconomb(String usconomb) {
        EntityManager em = getEntityManager();
        try {
            Usuacont usu = em.createNamedQuery("Usuacont.findByUsconomb", Usuacont.class).setParameter("usconomb", usconomb).getResultList().get(0);
            return usu;
        } finally {
            em.close();
        }
    }

    public boolean validateUserSignIn(String username, String password) {
        EntityManager em = getEntityManager();
        try {
            return (!em.createQuery("SELECT u FROM Usuacont u WHERE u.usconomb = :usconomb AND u.uscopass = :uscopass AND u.uscoesta = :uscoesta", Usuacont.class).setParameter("usconomb", username).setParameter("uscopass", password).setParameter("uscoesta", Constants.USER_ACTIVE).getResultList().isEmpty());
        } finally {
            em.close();
        }
    }

    public int getUsuacontCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Usuacont> rt = cq.from(Usuacont.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
